package com.example.chatroom.service.impl;

import com.example.chatroom.common.errorcode.ServiceErrorCodeConstants;
import com.example.chatroom.common.exception.ServiceException;
import com.example.chatroom.controller.param.GetMessagesParam;
import com.example.chatroom.dao.dataobject.MessageDO;
import com.example.chatroom.dao.dataobject.UserDO;
import com.example.chatroom.dao.mapper.MessageMapper;
import com.example.chatroom.dao.mapper.UserMapper;
import com.example.chatroom.service.IMessageService;
import com.example.chatroom.service.dto.GetMessagesDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MessageServiceImpl implements IMessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<GetMessagesDTO> getMessages(GetMessagesParam getMessagesParam) {
        log.info("getMessages getMessagesParam:{}",getMessagesParam);
        List<MessageDO> messageDOS=messageMapper.selectBySM(getMessagesParam.getSessionId());
        if(messageDOS.isEmpty()){
            log.info(ServiceErrorCodeConstants.MESSAGE_NOT_EXISTS.getMsg());
            throw new ServiceException(ServiceErrorCodeConstants.MESSAGE_NOT_EXISTS);
        }
        //构造返回结果
        return messageDOS.stream().map(messageDO -> {
            GetMessagesDTO getMessagesDTO=new GetMessagesDTO();
            getMessagesDTO.setId(messageDO.getId());
            getMessagesDTO.setGmtCreate(messageDO.getGmtCreate());
            getMessagesDTO.setFormId(messageDO.getFormId());
            UserDO userDO = userMapper.selectByPrimaryKey(messageDO.getFormId());
            getMessagesDTO.setFromName(userDO.getUserName());
            getMessagesDTO.setSessionId(messageDO.getSessionId());
            getMessagesDTO.setContent(messageDO.getContent());
            return getMessagesDTO;
        }).collect(Collectors.toList());
    }
}
